#!/usr/bin/env python3
import os
import subprocess
import zipfile
import shutil
import time
from datetime import datetime

start_python_time = time.time()

# H5项目的命令执行的跟路径
npm_build_directory = "/Users/liyadong/Desktop/WebWork/h5_trade_new"
stream_source_directory = os.path.join(npm_build_directory, "stream")
# 桌面路径
desktop_des_dir = "/Users/liyadong/Desktop/"

# Harmony项目配置文件的路径
hm_project_directory = "/Users/liyadong/Desktop/codeSpace/client_harmony_new/TZYJ_Harmony/entry/"
# 鸿蒙压缩文件的路径
zip_file_path = os.path.join(hm_project_directory, "src/main/resources/rawfile/stream.zip")
# 解压后的stream文件夹路径
unzip_stream_file_path = os.path.join(hm_project_directory, "src/main/resources/rawfile/stream")
# 解压后的路径
extract_directory = os.path.join(hm_project_directory, "src/main/resources/rawfile")


# 删除指定的压缩文件或者文件夹
def delete_files_in_directory(directory_path=extract_directory, is_compressed=False):
    if is_compressed:
        # 删除zip文件
        if os.path.exists(directory_path) and os.path.isfile(directory_path):
            os.remove(directory_path)
            print(f"已删除文件:{directory_path}")
        else:
            print(f"文件不存在或不是一个普通文件: {zip_file_path}")
    else:
        # print(f"文件不存在或不是一个普通文件: {zip_file_path}")
        if os.path.exists(directory_path) and os.path.isdir(directory_path):
            shutil.rmtree(directory_path)
            print(f"已删除 {directory_path}")
        else:
            print(f"{directory_path} 不存在")

#  解压stream.zip文件
def unzip_stream_action():
    if not os.path.exists(zip_file_path) or not os.path.isfile(zip_file_path):
        print(f"待解压文件不存在 {zip_file_path}")
        exit(1)
    try:
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
            zip_ref.extractall(extract_directory)
        print(f"已解压 {zip_file_path} 到当前目录 {extract_directory}")
    except zipfile.BadZipFile as e:
        print(f"解压失败，因为 {zip_file_path} 不是一个有效的ZIP文件: {e}")
    except Exception as e:
        print(f"解压过程中发生错误: {e}")
    macosx_folder_path = os.path.join(extract_directory, "__MACOSX")
    # 检查__MACOSX文件夹是否存在
    if os.path.exists(macosx_folder_path) and os.path.isdir(macosx_folder_path):
        # 删除__MACOSX文件夹及其所有内容
        shutil.rmtree(macosx_folder_path)
        print(f"已删除 {macosx_folder_path}")
    else:
        print(f"{macosx_folder_path} 不存在")

def do_stream_zip(): 
    # 验证stream文件夹是否存在
    if not os.path.exists(unzip_stream_file_path) or not os.path.isdir(unzip_stream_file_path):
        print(f"待压缩的stream文件夹不存在或不是一个目录: {unzip_stream_file_path}")
        exit(1)
    # 打开一个新的ZIP文件用于写入
    with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        # 遍历unzip_stream_file_path目录下的所有文件和子目录
        for root, dirs, files in os.walk(unzip_stream_file_path):
            # 计算每个文件或目录相对于unzip_stream_file_path的相对路径
            rel_path = os.path.relpath(root, unzip_stream_file_path)
            
            # 在ZIP文件中，为这些文件和目录添加一个前缀'stream/'
            # 注意：这里我们为根目录（即unzip_stream_file_path本身）添加'stream/'前缀
            # 对于其子目录和文件，它们将自动位于'stream/'之下
            arc_root = os.path.join('stream', rel_path) if rel_path != '.' else 'stream'
            
            # 为每个文件写入ZIP文件
            for file in files:
                file_path = os.path.join(root, file)
                arc_name = os.path.join(arc_root, file)  # 在ZIP文件中的完整路径
                zip_file.write(file_path, arc_name)
    
    print(f"压缩完成，输出文件为: {zip_file_path}")   

def executive_common_command(temp_commpand):
    try:
        subprocess.run(temp_commpand, cwd=npm_build_directory, check=True)
        print(f"{temp_commpand} 执行完成")
    except subprocess.CalledProcessError as e:
        print(f"{temp_commpand} 执行失败: {e}")
        exit(1)

# 将打包后的stream文件替换到对应的鸿蒙项目stream文件中去
def replace_sream_to_harmony_pj():
    # 确保源目录和目标目录存在
    if not os.path.exists(stream_source_directory):
        print(f"源目录不存在: {stream_source_directory}")
        exit(1)
    if not os.path.exists(unzip_stream_file_path):
        print(f"目标目录不存在: {unzip_stream_file_path}")
        exit(1)
    
    # 遍历源目录下的一级文件夹
    for item in os.listdir(stream_source_directory):
        source_item_path = os.path.join(stream_source_directory, item)
        target_item_path = os.path.join(unzip_stream_file_path, item)
    
        # 检查是否为文件夹
        if os.path.isdir(source_item_path):
            # 如果目标位置已有同名文件夹，则删除它
            if os.path.exists(target_item_path) and os.path.isdir(target_item_path):
                shutil.rmtree(target_item_path)
                print(f"已删除目标目录中的同名文件夹: {target_item_path}")
            else:
                print(f"目标目录中不存在同名文件夹,不需要给项目新增离线包: {target_item_path}")
                continue
            # 复制源文件夹到目标位置
            shutil.copytree(source_item_path, target_item_path)
            print(f"已复制文件夹到目标位置: {source_item_path} -> {target_item_path}")
    print("文件替换完成")

# 复制文件
def copy_folder_with_timestamp(source_folder, destination_dir):
    # 获取当前时间，并格式化为YYYYMMDD_HH_MM
    current_time = datetime.now().strftime("%Y%m%d_%H_%M")
    
    # 拼接新的文件夹名
    new_folder_name = f"{current_time}_stream"
    
    # 构建新的文件夹路径
    destination_folder = os.path.join(destination_dir, new_folder_name)
    
    # 复制文件夹
    try:
        shutil.copytree(source_folder, destination_folder)
        print(f"Folder {source_folder} has been copied to {destination_folder}")
    except Exception as e:
        print(f"An error occurred while copying the folder: {e}")

# 记录开始执行打包的时间
start_npm_build_time = time.time()
# 执行前端打包命令
executive_common_command(["npm", "run", "buildall"])

# 记录结束执行打包的时间
end_npm_build_time = time.time()

# 解压 stream.zip 文件
unzip_stream_action()

# 删除stream.zip文件
delete_files_in_directory(zip_file_path, True);

# 将打包后的stream文件替换到对应的鸿蒙项目stream文件中去
replace_sream_to_harmony_pj();

# 执行压缩
do_stream_zip()

# 删除stream文件
delete_files_in_directory(unzip_stream_file_path);

copy_folder_with_timestamp(stream_source_directory,desktop_des_dir)

# 记录其它操作结束时间
end_other_execu_time = time.time()
print(f"Python脚本执行总耗时: {end_other_execu_time - start_python_time}秒")
print(f"前端打包耗时: {end_npm_build_time - start_npm_build_time}秒")